package com.chinafree.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinafree.auth.model.bo.LoginUserBo;
import com.chinafree.auth.model.enumeration.VerficationEnum;
import com.chinafree.auth.model.param.RegistrationParam;
import com.chinafree.auth.model.result.LoginResult;
import com.chinafree.auth.service.LoginUserService;
import com.chinafree.auth.service.RegisterService;
import com.chinafree.auth.service.VerificationCode;
import com.chinafree.common.model.enumeration.ResponseCodeEnum;
import com.chinafree.common.model.response.BaseResponse;
import com.chinafree.common.model.response.EntityResponse;
import com.chinafree.common.utils.MD5Utils;
import com.chinafree.mapper.MaUserMapper;
import com.chinafree.model.po.MaUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private VerificationCode verificationCode;

    @Autowired
    private NormalLoginServiceImpl normalLoginService;

    @Autowired
    private LoginUserService loginUserService;

    @Autowired
    private MaUserMapper maUserMapper;

    @Override
    public BaseResponse sendRegisterVerificationCode(String phoneNumber) {
        return verificationCode.sendRegisterVerificationCode(VerficationEnum.REGISTER.getName(), phoneNumber);
    }


    @Override
    public EntityResponse<LoginResult> registerByPhoneAndCode(RegistrationParam body) {
        //1.校验验证码
        if (body.getPhoneNumber() == null) {
            return new EntityResponse<>(ResponseCodeEnum.SUCCESS, "未填写手机号", null);
        }
        String msg = verificationCode.checkVerificationCode(VerficationEnum.REGISTER.getName(), body.getPhoneNumber(), body.getVerification());
        if (msg != null) {
            return new EntityResponse<>(ResponseCodeEnum.FORBIDDEN, msg, null);
        }
        //2.快速注册（插入数据库）
        String userMsg = createUser(body);
        if(userMsg!=null){
            return new EntityResponse<>(ResponseCodeEnum.FORBIDDEN, userMsg, null);
        }
        String phoneNumber = body.getPhoneNumber();
        Optional<LoginUserBo> loginUserByLoginMobile1 = loginUserService.getLoginUserByLoginMobile(phoneNumber);
        if (!loginUserByLoginMobile1.isPresent()) {
            return new EntityResponse<>(ResponseCodeEnum.FORBIDDEN, "插入数据库失败", null);
        }
        return normalLoginService.getLoginResult(loginUserByLoginMobile1.get(), body.getRoleId());
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
    String createUser(RegistrationParam body) {
        MaUser build = MaUser.builder()
                .phone(body.getPhoneNumber())
                .password(body.getPassword() == null ? null : MD5Utils.hash(body.getPassword()))
                .build();
        MaUser sysLoginUser = maUserMapper.selectOne(new QueryWrapper<MaUser>().eq("phone", body.getPhoneNumber()));
        if (sysLoginUser != null) {
           return  "手机号已注册";
        }
        maUserMapper.insert(build);
        return null;
    }
}
